<template>
  <form-item-wrapper
    :designer="designer"
    :field="field"
    :rules="rules"
    :design-state="designState"
    :parent-widget="parentWidget"
    :parent-list="parentList"
    :index-of-parent-list="indexOfParentList"
    :sub-form-row-index="subFormRowIndex"
    :sub-form-col-index="subFormColIndex"
    :sub-form-row-id="subFormRowId"
  >
    <template v-if="!field.options.hiddenField">
      <!-- modify by weig 2025-04-07 处理表单打印的时候字体大小显示不对以及文本对齐方式不对的bug -->
      <span
        v-if="isReadMode"
        class="readonly-mode-field"
        :style="{
          fontSize: `${field.options.fontSize}px`,
          textAlign: field.options.contentAlign,
          width: '100%'
        }"
      >
        {{ displayText }}
      </span>
      <!-- 单选框 -->
      <el-input
        v-else-if="field.options.label !== '客户' && field.options.label !== '开发令'"
        ref="fieldEditor"
        v-model="fieldModel"
        :disabled="field.options.disabled"
        :readonly="field.options.readonly"
        :size="field.options.size"
        :title="fieldModel || ''"
        class="hide-spin-button"
        :type="inputType"
        :style="{ 'font-size': `${field.options.fontSize}px`, 'font-family': `${field.options.fontFamily}` }"
        :show-password="field.options.showPassword"
        :placeholder="placeholderLang"
        :clearable="field.options.clearable"
        :minlength="field.options.minLength"
        :maxlength="field.options.maxLength"
        :show-word-limit="field.options.showWordLimit"
        @focus="handleFocusCustomEvent"
        @blur="handleBlur"
        @input="handleInputCustomEvent"
        @change="handleChangeEvent"
      >
        <template #prefix v-if="field.options.prefixIcon">
          <component style="width: 15px; height: 15px" :is="field.options.prefixIcon" />
        </template>
        <template #suffix v-if="field.options.suffixIcon">
          <component style="width: 15px; height: 15px" :is="field.options.suffixIcon" />
        </template>
        <template #append v-if="field.options.appendButton">
          <el-button :disabled="field.options.disabled || field.options.appendButtonDisabled" @click="emitAppendButtonClick">
            <el-icon>
              <component :is="field.options.buttonIcon" />
            </el-icon>
          </el-button>
        </template>
      </el-input>
      <!-- 多选框 -->
      <el-select
      v-else-if="field.options.label === '客户'"
      ref="fieldEditor"
      v-model="fieldModel"
      :disabled="field.options.disabled"
      :size="field.options.size"
      :style="{
        'font-size': `${field.options.fontSize}px`,
        'font-family': `${field.options.fontFamily}`,
        'text-align': field.options.contentAlign
      }"
      placeholder="请输入关键字查询"
      :clearable="field.options.clearable ?? true"
      v-loading="customerLoading"
      filterable
      remote
      :remote-method="fetchCustomerOptions"
      @focus="handleFocusCustomEvent"
      @blur="handleBlur"
      @change="handleChangeEvent"
      >
      <el-option
    v-for="item in customerOptions"
    :key="item.value"
    :label="item.label"
    :value="item.label"
  />
      </el-select>
            <el-select
      v-else-if="field.options.label === '开发令'"
      ref="fieldEditor"
      v-model="fieldModel"
      :disabled="field.options.disabled"
      :size="field.options.size"
      :style="{
        'font-size': `${field.options.fontSize}px`,
        'font-family': `${field.options.fontFamily}`,
        'text-align': field.options.contentAlign
      }"
      placeholder="请输入关键字查询"
      :clearable="field.options.clearable ?? true"
      v-loading="DevelopmentOrderLoading"
      filterable
      remote
      :remote-method="fetchCustomerOptionsA"
      @focus="handleFocusCustomEvent"
      @blur="handleBlur"
      @change="handleChangeEvent"
      >
      <el-option
    v-for="item in DevelopmentOrderOptions"
    :key="item.value"
    :label="item.label"
    :value="item.label"
  />
      </el-select>
    </template>
  </form-item-wrapper>
</template>

<script>
import formDesigner from '@common/form-designer';
import core from '@common/core'
const request = core.getExportResource('src/core/utils/http-tools.js').default;

// import FormItemWrapper from '@/form-designer/extension/form-designer/rewrite-field-widget/form-item-wrapper';
const FormItemWrapper = formDesigner.getExportResource('src/form-designer/extension/form-designer/rewrite-field-widget/form-item-wrapper.vue').default;
// import InputWidget from '@/form-designer/components/form-designer/form-widget/field-widget/input-widget';
const InputWidget = formDesigner.getExportResource('src/form-designer/components/form-designer/form-widget/field-widget/input-widget.vue').default;
// import { deepClone } from '@/form-designer/utils/util';
const { deepClone }  = formDesigner.getExportResource(
  'src/form-designer/utils/util.js'
);
console.log("测试input组件替换🤑");
export default {
  name: 'input-widget-rewrite',
  extends: InputWidget,
  data() {
  return {
    customerOptions: [],   // 下拉备选——客户
    customerLoading: false,   // <-- 新增
    DevelopmentOrderOptions: [],   // 下拉备选——开发令
    DevelopmentOrderLoading: false,   // <-- 新增
  };
},
  components: { FormItemWrapper },
  watch: {
    'field.options.fontFamily': function (newVal) {
      if (this.$refs.fieldEditor && this.$refs.fieldEditor.input) {
        this.$refs.fieldEditor.input.style.fontFamily = newVal;
      }
    },
    'field.options.contentAlign': function (newVal) {
      if (this.$refs.fieldEditor && this.$refs.fieldEditor.input) {
        this.$refs.fieldEditor.input.style.textAlign = newVal;
      }
    }
  },
  computed: {
    displayText() {
      return this.fieldModel;
    }
  },
  methods: {
    // 多选——客户
    async fetchCustomerOptions(clientName) {
  if (!clientName) { this.customerOptions = []; return; }

  this.customerLoading = true;                 // 开始加载
  try {
    const res = await request({
      method: 'get',
      url: '/rest/process/v1/getClientCodeList',
      params: { clientName }
    });
    const list = res.data?.data || [];
    this.customerOptions = list.map(item => ({
      label: item.text,
      value: item.clientCode
    }));
  } 
  catch{
    this.$message.warning('加载超时，请稍后！');
  }
  finally {
    this.customerLoading = false;              // 结束加载
  }
},
    //多选——开发令
    async fetchCustomerOptionsA(keword) {
  if (!keword) { this.DevelopmentOrderOptions = []; return; }

  this.DevelopmentOrderLoading = true;                 // 开始加载
  try {
    const res = await request({
      method: 'get',
      url: '/rest/process/v1/getDevelopmentOrderList',
      params: { keword }
    });
    const list = res.data?.data || [];
    this.DevelopmentOrderOptions = list.map(item => ({
      label: item.key,
      value: item.key
    }));
  } 
  catch{
    this.$message.warning('加载超时，请稍后！');
  }
  finally {
    this.DevelopmentOrderLoading = false;              // 结束加载
  }
},
    /**
     * @function handleFormAttrMapper
     * @description 映射表单属性到表单模板
     * @author cuiwb
     * @param {*} val 表单对象
     * @return {*}
     */
    handleFormAttrMapper(val) {
      if (this.field?.options?.formAttrMapper) {
        const mapperAttr = this.field?.options?.formAttrMapper;
        if (val) {
          let ps = ['baseData', 'classifyIba', 'typeIba'];
          let value = null;
          let targetP = ps.find(p => {
            if (val[p] && val[p][mapperAttr]) {
              if (['classifyIba', 'typeIba'].indexOf(p) > -1) {
                value = val[p][mapperAttr].join(',');
              } else {
                value = val[p][mapperAttr];
              }
              return true;
            }
          });
          if (targetP && value) {
            this.fieldModel = value;
            this.handleChangeEvent(value);
          }
        }
      }
    },
    /**
     * @description 输入框失焦时去除首尾空格
     * @author nieyz
     * @Date 2025-5-20 17:37:43
     * @param event 失焦事件参数
     */
    handleBlur(event) {
      // 如果是字符串值，去掉首尾空格
      if (Object.prototype.toString.call(this.fieldModel) === '[object String]') {
        this.fieldModel = this.fieldModel.trim();
        this.handleChangeEvent(this.fieldModel);
      }
      this.handleBlurCustomEvent(event)
    }
  },
  mounted() {
    console.log('当前字段信息：', this.field);
    console.log('当前字段信息：', this.field.options.label);
    this.field.options.value = 123;
    if (this.$refs.fieldEditor && this.$refs.fieldEditor.input) {
      this.$refs.fieldEditor.input.style.fontFamily = this.field.options.fontFamily;
      this.$refs.fieldEditor.input.style.textAlign = this.field.options.contentAlign;
    }
    // 注册表单属性到表单模板映射事件
    window.$wujie?.bus?.$on('sendFormDataMapper', this.handleFormAttrMapper);
    this.setInitDisplayText(deepClone(this.displayText));
  },
  beforeDestroy() {
    window.$wujie?.bus?.$off('sendFormDataMapper', this.handleFormAttrMapper);
  },
};
</script>

<style lang="scss" scoped></style>
